Ext.extend(app.module,{
    currentFormValues: {},
    init: function(){
        var main = this;
        //用于列表
        this.ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'student/students.do'}),
            reader: new Ext.data.JsonReader({
                totalProperty: 'total',
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'cardid'},
                {name:'number'},
                {name:'username'},
                {name:'sex'},
                {name:'classid'},
                {name:'phone'},
                {name:'email'},
                {name:'classname'}
            ])
        });
        // 翻页排序时带上查询条件
        this.ds.on('beforeload', function() {
            this.baseParams = {
                cardid : Ext.getCmp('queryStudentCardid').getValue(),
                number : Ext.getCmp('queryStudentNumber').getValue(),
                username : Ext.getCmp('queryStudentName').getValue(),
                classids : Ext.getCmp('queryClass').getValue()
            };
        });
        this.loader = new Ext.tree.TreeLoader({dataUrl:'class/getClassTree.do'});
        this.loader.processResponse = function(response, node, callback){
            var json = response.responseText;
            try{
                var json = eval("(" + json + ")");
                node.beginUpdate();
                var o = json["key"];
                for(var i=0,len=o.length; i<len; i++){
                    var n = this.createNode(o[i]);
                    if(n){
                        node.appendChild(n);
                    }
                }
                node.endUpdate();
                if(typeof callback == "function"){
                    callback(this,node);
                }
            } catch(e) {
                this.handleFailure(response);
            }
        }
        classTree = new Ext.tree.TreePanel( {
            loader: main.loader,
            root : {
                id: 0,
                text: '根节点',
                expanded: true
            },
            autoScroll : false,
            rootVisible : false,// 根节点是否可见
            animate : false,    // 展开,收缩动画
            useArrows : false,  // 是否使用箭头样式
            lines:false,        // 去掉树的线
            border : false
        });
        // 监听下拉树的节点单击事件
        classTree.on('click', function(node) {
            //递归获取所有子节点
            var getChild = function(n){
                if(!n.leaf){
                    var nodes = n.childNodes;
                    for(var i=0;i<nodes.length;i++){
                        classids.push(nodes[i].id);
                        getChild(nodes[i]);
                    }
                }
            }
            var classids = [];
            classids.push(node.id);
            getChild(node);
            main.comboxWithTree.setValue(node.text);
            Ext.getCmp('queryClass').setValue(classids);
            main.comboxWithTree.collapse();
        });
        this.comboxWithTree = new Ext.form.ComboBox({
            store : new Ext.data.SimpleStore( {
                fields : [],
                data : [[]]
            }),
            autoScroll : true,
            value : ' ',
            emptyText : '请选择...',
            mode : 'local',
            editable: false,
            triggerAction : 'all',
            maxHeight : 390,
            // 下拉框的显示模板,classTreeDiv作为显示下拉树的容器
            tpl : "<tpl for='.'><div style='height:390px'><div id='classTreeDiv'></div></div></tpl>",
            onSelect : Ext.emptyFn,
            onViewClick : Ext.emptyFn,
            assertValue : Ext.emptyFn
        });
        // 监听下拉框的下拉展开事件
        this.comboxWithTree.on('expand', function() {
            // 将树挂到treeDiv容器
            classTree.render('classTreeDiv');
        });

        var student_pagesize_combo = new Ext.form.ComboBox( {       //设置分页栏的每页记录数选择
            name : 'pagesize',
            hiddenName : 'pagesize',
            typeAhead : true,
            triggerAction : 'all',
            lazyRender : true,
            mode : 'local',
            store : new Ext.data.ArrayStore(
                {
                    fields : [ 'value', 'text' ],
                    data : [ [ 50, '50条/页' ], [ 100, '100条/页' ],
                        [ 200, '200条/页' ], [ 300, '300条/页' ],
                        [ 500, '500条/页' ], [ 2000, '1000条/页' ] ]
                }),
            valueField : 'value',
            displayField : 'text',
            value : '50',
            editable : false,
            width : 85
        });
        var number = parseInt(student_pagesize_combo.getValue());

        student_pagesize_combo.on("select", function(comboBox) {
            var bbar = Ext.getCmp('studentbbar');
            bbar.pageSize = parseInt(comboBox.getValue());
            number = parseInt(comboBox.getValue());
            main.ds.reload( {
                params : {
                    start : 0,
                    limit : bbar.pageSize
                }
            });
        });

        this.sm = new Ext.grid.CheckboxSelectionModel();
        this.body = new Ext.grid.GridPanel({
            store: this.ds,
            region: 'center',
            loadMask: true,
            viewConfig:{
                forceFit:true
            },
            sm: this.sm,
            columns: [
                new Ext.grid.RowNumberer(),
                this.sm,
                {
                    xtype: 'gridcolumn',
                    dataIndex: 'id',
                    header: 'id',
                    hidden: true
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'cardid',
                    header: '身份证',
                    width: 180
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'number',
                    header: '学号',
                    width: 100
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'username',
                    header: '姓名',
                    width: 80
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'sex',
                    header: '性别',
                    width: 50,
                    renderer:function(value, cellmeta, record, rowIndex, columnIndex, store){
                        if(value==1) return '男';
                        else if(value==0) return '女';
                        else return '';
                    }
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'classid',
                    hidden: true
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'classname',
                    header: '班级',
                    width: 100
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'phone',
                    header: '电话',
                    width: 120
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'email',
                    header: '邮箱',
                    width: 120
                }
            ],
            tbar: {
                xtype: 'toolbar',
                items: [
                    {
                        text: '新增',
                        iconCls : 'btn-new',
                        scope: this,
                        handler: this.add
                    },
                    '-',
                    {
                        text: '修改',
                        iconCls : 'btn-edit',
                        scope: this,
                        handler: this.edit
                    },
                    '-',
                    {
                        text: '删除',
                        iconCls : 'btn-del',
                        scope: this,
                        handler: this.del
                    },
                    '-',
                    {
                        text: '重置密码',
                        iconCls : 'btn-undo',
                        scope: this,
                        handler: this.resetPass
                    },
                    '-',
                    {
                        text: '关联试卷',
                        iconCls : 'btn-save',
                        scope: this,
                        handler: function(){
                            if (this.body.getSelectionModel().hasSelection()) {
                                this.paperDlg = this.getPaperDlg();
                                this.paperDlg.show();
                            } else {
                                Ext.Msg.alert('信息', '请选择需要关联试卷的考生！');
                            }
                        }
                    },
                    '->',
                    {
                        xtype: 'displayfield',
                        value: '查询条件：'
                    },
                    this.comboxWithTree,
                    {
                        xtype: 'textfield',
                        id : 'queryClass',
                        hidden: true
                    },
                    ' ',
                    {
                        xtype: 'textfield',
                        id : 'queryStudentCardid',
                        name : 'queryStudentCardid',
                        emptyText : '请输入身份证号码',
                        enableKeyEvents : true,
                        listeners : {
                            specialkey : function(field, e) {
                                if (e.getKey() == Ext.EventObject.ENTER) {
                                    main.query();
                                }
                            }
                        },
                        width : 80
                    },
                    ' ',
                    {
                        xtype: 'textfield',
                        id : 'queryStudentNumber',
                        name : 'queryStudentNumber',
                        emptyText : '请输入学号',
                        enableKeyEvents : true,
                        listeners : {
                            specialkey : function(field, e) {
                                if (e.getKey() == Ext.EventObject.ENTER) {
                                    main.query();
                                }
                            }
                        },
                        width : 80
                    },
                    ' ',
                    {
                        xtype: 'textfield',
                        id : 'queryStudentName',
                        name : 'queryStudentName',
                        emptyText : '请输入姓名',
                        enableKeyEvents : true,
                        listeners : {
                            specialkey : function(field, e) {
                                if (e.getKey() == Ext.EventObject.ENTER) {
                                    main.query();
                                }
                            }
                        },
                        width : 80
                    },
                    {
                        text : '查询',
                        iconCls : 'btn-search',
                        handler : function() {
                            main.query();
                        }
                    }

                ]
            },
            bbar: {
                id: 'studentbbar',
                xtype: 'paging',
                pageSize : number,
                store : this.ds,
                displayInfo : true,
                displayMsg : '显示{0}条到{1}条,共{2}条',
                emptyMsg : "没有符合条件的记录",
                items : [ '-', '&nbsp;&nbsp;', student_pagesize_combo ]
            }
        });
        this.main.add(this.body);
        this.main.doLayout();
        this.ds.load({
            params: {
                start:0,
                limit:50
            }
        });
    },
    //关联试卷窗口
    getPaperDlg: function(){
        this.paperForm = this.getPaperForm();
        var paperDlg = new Ext.Window({
            height: 130,
            width: 320,
            layout: 'fit',
            border: false,
            frame: true,
            title: '',
            modal: true,
            plain: true,
            resizable: false,
            items: [this.paperForm],
            listeners: {
                scope: this,
                render: function(fp){
                    this.paperForm.getForm().waitMsgTarget = fp.getEl();
                },
                show: function(){
                    var f = this.paperForm.getForm();
                    f.clearInvalid();
                }
            }
        });
        return paperDlg;
    },
    getPaperForm: function(){
        //试卷选择的store
        var paperStore = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'paper/getNotEndPaper.do'}),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'}
            ])
        });
        //试卷选择的下拉框
        var comboPaper = new Ext.form.ComboBox({
            store: paperStore,
            editable: false,
            emptyText: '请选择试卷...',
            allowBlank: false,
            mode: 'remote',
            hiddenName : 'paperid',
            typeAhead : true,
            triggerAction : 'all',
            displayField: 'name',
            valueField: 'id',
            fieldLabel: '关联试卷'
        });
        var paperForm = new Ext.form.FormPanel({
            defaultType: 'textfield',
            bodyStyle: 'padding:5px',
            buttonAlign: 'center',
            url:'student/glPaper.do',
            labelWidth: 80,
            defaults: {
                anchor: '90%'
            },
            items: [comboPaper],
            buttons: [
                {
                    text: '确定',
                    scope: this,
                    handler: function() {
                        this.glSubmit();
                    }
                },
                {
                    text: '取消',
                    scope: this,
                    handler: function() {
                        this.paperDlg.hide();
                    }
                }
            ]
        });
        return paperForm;
    },
    getDialog: function(){
        this.form = this.getForm();
        var dlg = new Ext.Window({
            height: 300,
            width: 400,
            layout: 'fit',
            border: false,
            frame: true,
            title: '',
            modal: true,
            plain: true,
            resizable: false,
            items: [this.form],
            listeners: {
                scope: this,
                render: function(fp){
                    this.form.getForm().waitMsgTarget = fp.getEl();
                },
                show: function(){
                    var f = this.form.getForm();
                    f.setValues(this.currentFormValues);
                    f.clearInvalid();
                }
            }
        });
        return dlg;
    },
    getForm: function() {
        var main = this;
        selectclassTree = new Ext.tree.TreePanel( {
            loader: this.loader,
            root : {
                id: 0,
                text: '根节点',
                expanded: true
            },
            autoScroll : false,
            rootVisible : false,// 根节点是否可见
            animate : false,    // 展开,收缩动画
            useArrows : false,  // 是否使用箭头样式
            lines:false,        // 去掉树的线
            border : false
        });
        // 监听下拉树的节点单击事件
        selectclassTree.on('click', function(node) {
            if(node.leaf){
                main.comboxWithclassTree.setValue(node.text);
                Ext.getCmp('ssclass').setValue(node.id);
                main.comboxWithclassTree.collapse();
            } else {
                Ext.Msg.alert("提示","只能选择子节点！");
            }
        });
        this.comboxWithclassTree = new Ext.form.ComboBox({
            fieldLabel: '所属班级',
            store : new Ext.data.SimpleStore( {
                fields : [],
                data : [[]]
            }),
            autoScroll : true,
            value : '',
            emptyText : '请选择...',
            mode : 'local',
            editable: false,
            triggerAction : 'all',
            maxHeight : 390,
            // 下拉框的显示模板,classTreeDiv作为显示下拉树的容器
            tpl : "<tpl for='.'><div style='height:390px'><div id='selectclassTreeDiv'></div></div></tpl>",
            allowBlank : false,
            onSelect : Ext.emptyFn,
            onViewClick : Ext.emptyFn,
            assertValue : Ext.emptyFn
        });

        // 监听下拉框的下拉展开事件
        this.comboxWithclassTree.on('expand', function() {
            // 将树挂到treeDiv容器
            selectclassTree.render('selectclassTreeDiv');
        });
        var form = new Ext.form.FormPanel({
            defaultType: 'textfield',
            bodyStyle: 'padding:5px',
            buttonAlign: 'center',
            url:'student/save.do',
            labelWidth: 80,
            defaults: {
                anchor: '90%'
            },
            items: [
                {
                    xtype: 'hidden',
                    name: 'id'
                },
                {
                    xtype: 'textfield',
                    name: 'cardid',
                    allowBlank: false,
                    maxLength: 18,
                    regex: /[\d]{6}(19|20)*[\d]{2}((0[1-9])|(11|12))([012][\d]|(30|31))[\d]{3}[xX\d]*/,
                    regexText: '请输入正确的18位身份证号码！',
                    emptyText: '身份证号码不能为空',
                    fieldLabel: '身份证'
                },
                {
                    xtype: 'textfield',
                    name: 'number',
                    regex: /^[0-9]*$/,
                    regexText: '学号只能是数字！',
                    emptyText: '请输入学号...',
                    fieldLabel: '学号'
                },
                {
                    xtype: 'textfield',
                    name: 'username',
                    allowBlank: false,
                    regex: /^[\u4e00-\u9fa5]+$/,
                    regexText: '姓名只能为中文！',
                    emptyText: '姓名不能为空',
                    fieldLabel: '姓名'
                },
                {
                    xtype: 'textfield',
                    name: 'classid',
                    id: 'ssclass',
                    hidden: true
                },
                this.comboxWithclassTree,
                {
                    xtype: 'textfield',
                    name: 'phone',
                    regex: /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
                    regexText: '请输入正确的电话号码！',
                    emptyText: '请输入电话号码...',
                    fieldLabel: '电话号码'
                },
                {
                    xtype: 'textfield',
                    name: 'email',
                    vtype: 'email',
                    emptyText: '请输入电子邮箱...',
                    fieldLabel: '电子邮箱'
                }
            ],
            buttons: [{
                text: '确定',
                scope: this,
                handler: function() {
                    this.submit();
                }
            },
                {
                    text: '重置',
                    scope: this,
                    handler: function() {
                        var f = this.form.getForm();
                        f.reset();
                        f.setValues(this.currentFormValues);
                        f.clearInvalid();
                    }
                }]
        });
        return form;
    },
    submit: function(){
        if (this.form.getForm().isValid()) {
            var id = this.form.getForm().findField("id").getValue();
            this.form.getForm().submit({
                waitTitle: '保存数据',
                waitMsg: '正在保存……',
                scope: this,
                method: 'post',
                params: '',
                submitEmptyText: false,     //禁止提交emptyText
                success: function(form, action) {
                    var info = action.result.info;
                    if (action.result.success) {
                        this.ds.reload();
                        if (action.result.method == "Create") {
                            this.form.getForm().reset();
                        } else {
                            this.dlg.hide();
                        }
                    }
                    Ext.Msg.alert('信息', info);
                },
                failure: function(form, action) {
                    var info = action.result.info;
                    Ext.Msg.alert('提示', info);
                }
            });
        }
    },
    glSubmit: function(){
        main = this;
        Ext.Msg.confirm('关联试卷', '确定将选中考生关联到该试卷？',
            function(btn) {
                if (btn == 'yes') {
                    var recs = main.body.getSelectionModel().getSelections();
                    var ids = [];
                    var titles = [];
                    for (var i = 0; i < recs.length; i++) {
                        var data = recs[i].data;
                        ids.push(data.id);
                    }
                    main.paperForm.getForm().submit({
                        waitTitle: '保存数据',
                        waitMsg: '正在保存……',
                        scope: main,
                        method: 'post',
                        params: {ids: ids.toString()},
                        submitEmptyText: false,     //禁止提交emptyText
                        success: function(form, action) {
                            var info = action.result.info;
                            Ext.Msg.alert('信息', info);
                            paperDlg.hide();
                        },
                        failure: function(form, action) {
                            var info = action.result.info;
                            Ext.Msg.alert('提示', info);
                        }
                    });
                }
            }
        );
    },
    add: function() {
        this.dlg = this.getDialog();
        Ext.apply(this.currentFormValues, {
            id: '',
            cardid: '',
            classid: '',
            number: '',
            username: '',
            phone:'',
            email:''
        });
        this.comboxWithclassTree.setValue('');
        this.dlg.setTitle("增加考生");
        this.dlg.show();
    },

    edit: function() {
        this.dlg = this.getDialog();
        var recs = this.body.getSelectionModel().getSelections();
        if (recs.length==0) {
            Ext.Msg.alert('信息', '请选择要编辑的考生。');
        } else if(recs.length>1) {
            Ext.Msg.alert('信息', '只能选择一个考生进行编辑。');
        } else {
            this.dlg.setTitle("编辑考生");
            Ext.apply(this.currentFormValues, {
                id: recs[0].data.id,
                cardid: recs[0].data.cardid,
                classid: recs[0].data.classid,
                number: recs[0].data.number,
                username: recs[0].data.username,
                phone: recs[0].data.phone,
                email: recs[0].data.email
            });
            this.comboxWithclassTree.setValue(recs[0].data.classname);
            this.dlg.show();
        }
    },

    del: function() {
        var main = this;
        if (this.body.getSelectionModel().hasSelection()) {
            var recs = this.body.getSelectionModel().getSelections();
            var ids = [];
            var titles = [];
            for (var i = 0; i < recs.length; i++) {
                var data = recs[i].data;
                ids.push(data.id);
                titles.push(data.name);
            }
            Ext.Msg.confirm('删除考生', '确定删除以下考生？<br><font color="red">' + titles.toString() + '</font>',
                function(btn) {
                    if (btn == 'yes') {
                        Ext.Ajax.request({
                            method:'post',
                            url:'student/remove.do',
                            params:{
                                ids:ids.toString()
                            },
                            scope: main,
                            success: function(resp, opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                if(result.success=='true') {
                                    this.ds.reload();
                                    Ext.Msg.alert('信息', info);
                                }else {
                                    Ext.Msg.alert('信息', info);
                                }
                            },
                            failure: function(resp,opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                Ext.Msg.alert('提示', info);
                            }
                        });
                    }
                });
        } else {
            Ext.Msg.alert('信息', '请选择要删除的考生！');
        }
    },
    query: function(){
        this.ds.load( {
            params : {
                start : 0,
                limit : Ext.getCmp('studentbbar').pageSize,
                cardid : Ext.getCmp('queryStudentCardid').getValue(),
                number : Ext.getCmp('queryStudentNumber').getValue(),
                username : Ext.getCmp('queryStudentName').getValue(),
                classids : Ext.getCmp('queryClass').getValue()
            }
        });
    },
    resetPass: function(){
        var main = this;
        if (this.body.getSelectionModel().hasSelection()) {
            var recs = this.body.getSelectionModel().getSelections();
            var ids = [];
            var titles = [];
            for (var i = 0; i < recs.length; i++) {
                var data = recs[i].data;
                ids.push(data.id);
                titles.push(data.name);
            }
            Ext.Msg.confirm('重置密码', '确定将以下考生密码重置？<br><font color="red">' + titles.toString() + '</font>',
                function(btn) {
                    if (btn == 'yes') {
                        Ext.Ajax.request({
                            method:'post',
                            url:'student/resetPass.do',
                            params:{
                                ids:ids.toString()
                            },
                            scope: main,
                            success: function(resp, opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                if(result.success=='true') {
                                    this.ds.reload();
                                    Ext.Msg.alert('信息', info);
                                }else {
                                    Ext.Msg.alert('信息', info);
                                }
                            },
                            failure: function(resp,opts) {
                                var result = Ext.util.JSON.decode(resp.responseText);
                                var info = result.info;
                                Ext.Msg.alert('提示', info);
                            }
                        });
                    }
            });
        } else {
            Ext.Msg.alert('信息', '请选择密码重置的考生！');
        }
    }
});